const express = require('express')
const router = express.Router()
const db = require('../mysql')
// 生成jwt包
const jwt = require('jsonwebtoken')
// 创建jwt密钥
const secretkey = 'sakura-snows'
// TODO:sql语句
// 查询用户是否存在语句(注册)
const finduser = 'SELECT * FROM user_book WHERE user_phone = ?'
// 用户注册语句(注册)
const regiser = 'INSERT INTO user_book  VALUES (?, ?, ?)'
// 校验账号，密码是否正确(登录)
const verifyact = 'SELECT * FROM user_book WHERE user_phone = ? and password = ?'
// 修改密码
const pwdupd = 'UPDATE user_book SET password=? WHERE user_phone=?'
// TODO:用户注册 (user_phone,password)
router.post('/register', (req, res) => {
  let user_phone = req.body.user_phone
  // 插入数据
  let userdatas = {
    nickname:user_phone.slice(-4),
    password: req.body.password,
    user_phone
  }
  db.query(finduser, user_phone, (err, result) => {
    if (err) return err.message
    if (result.length > 0) {  // 如有有结果，则说明有数据存在
      res.send({
        message: '用户已存在',
        status: 303 
      })
    } else {
      // 插入用户注册信息
      db.query(regiser, [userdatas.nickname,userdatas.password,userdatas.user_phone], (err, result) => {
        if (err) return err.message
        if (result.affectedRows == 1) {
          res.send({
            message: '注册成功',
            status: 200
          })
        }
      })
    }
  })
})

// TODO:用户登录(user_phone,password)
router.post('/login', (req, res) => {
  const userinfo = {
    user_phone: req.body.user_phone,
    password:req.body.password
  }
  const tokenstr = jwt.sign({username:userinfo.uname},secretkey,{expiresIn:'3h'})
  db.query(verifyact, [userinfo.user_phone, userinfo.password], (err, result) => {
    if (err) return err.message
    let resdata = JSON.parse(JSON.stringify(result))
    if (result.length > 0) {
      res.send({
        message: '正确',
        status: 200,
        user_phone:userinfo.user_phone,
        nickname:resdata[0].nickname,
        token: tokenstr,
      })
    } else {
      res.send({
        message: '账号或密码错误',
        status:303
      })
    }
  })

})
// TODO: 用户修改密码(user_phone,password)
router.post('/changepwd', (req, res) => {
  const userinfo = {
    user_phone: req.body.user_phone,
    oldpassword: req.body.oldpassword,
    newpassword:req.body.newpassword
  }
  db.query(verifyact, [userinfo.user_phone,userinfo.oldpassword], (err, result) => {
    if (err) return err.message
    if (result.length>0) {
    
      db.query(pwdupd, [userinfo.newpassword, userinfo.user_phone], (err, result) => {
        if (err) return err.message
        if (result.affectedRows == 1) {
          res.send({message:'密码更新成功',status:200})
        }
      })
    } else {
      res.send({message:'原密码错误',status:303})
    }
  })
})

module.exports = router